package com.liuzy.util;

import java.util.Collections;
import java.util.HashSet;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.ConcurrentLinkedQueue;

/**
 *
 * @author liuzy
 * @since 2015年9月19日
 */
public class UrlQueue {

	public Set<String> history = Collections.synchronizedSet(new HashSet<String>());

	private Queue<String> queue = new ConcurrentLinkedQueue<String>();

	private int size = 10000;

	public boolean add(String url) {
		if (url != null && !history.contains(url)) {
			synchronized (queue) {
				if (queue.size() <= size) {
					if (queue.offer(url)) {
						history.add(url);
					}
					return true;
				} else {
					queue.poll();
					queue.offer(url);
				}
			}
		}
		return false;
	}

	public String get() {
		synchronized (queue) {
			if (queue.isEmpty()) {
				return null;
			} else {
				return queue.poll();
			}
		}
	}

	public void clear() {
		queue.clear();
	}

}
